package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dao.EmployeeDao;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.NameExistException;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired(required = false)
    private EmployeeDao employeeDao;
    @Override
    public R<Employee> login(Employee employee) {
        Employee emp = employeeDao.findByName(employee);
        if (emp == null) {
            return R.error("用户不存在");
        }
        String inputPwd = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        if (!emp.getPassword().equals(inputPwd)) {
            return R.error("用户密码错误");
        }
        if (emp.getStatus() == 0) {
            return R.error("用户被禁用");
        }
        return R.success(emp);
    }

    @Override
    public void save(Employee employee) {
        // 查询用户是否存在，若已存在抛出异常
        Employee name = employeeDao.findByName(employee);
        if (name != null) {
            throw new NameExistException(employee.getUsername());
        }
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(1);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employeeDao.save(employee);
    }

    @Override
    public Page<Employee> findByPage(Integer page, Integer pageSize, String name) {
        // pageHelper 设置页面大小
        PageHelper.startPage(page, pageSize);
        // 查询数据
        List<Employee> employeeList = employeeDao.findByPage(name);
        // 封装pageInfo对象
        PageInfo<Employee> pageInfo = new PageInfo<>(employeeList);
        // 装化成page对象
        Page<Employee> pageResult = new Page<>();
        pageResult.setPage(pageInfo.getPageNum());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setRecords(pageInfo.getList());
        pageResult.setTotal(pageInfo.getTotal());
        return pageResult;
    }

    @Override
    public void update(Employee employee) {
        employeeDao.updateById(employee);
    }

    @Override
    public Employee findById(Integer id) {

        Employee employee = employeeDao.findById(id);
        return employee;
    }
}
